package com.chinaisafe.user.biz.impl;

import cn.hutool.core.lang.Assert;
import com.chinaisafe.module.user.response.SysRoleRespVO;
import com.chinaisafe.user.biz.SysRoleBiz;
import com.chinaisafe.user.entity.SysRole;
import com.chinaisafe.user.entity.SysUser;
import com.chinaisafe.user.entity.SysUserRole;
import com.chinaisafe.user.mapper.SysUserRoleMapper;
import com.chinaisafe.user.service.SysRoleService;
import com.chinaisafe.user.service.SysUserRoleService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * SysRoleBizImpl
 * Description：
 * 角色管理
 * @author tby
 * @date 2024/7/13 16:41
 */
@Service
public class SysRoleBizImpl implements SysRoleBiz {
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysUserRoleService sysUserRoleService;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void enableSwitch(Long id) {
        SysRole sysRole = sysRoleService.getById(id);
        if (sysRole.getEnable()){
            Long userCount = sysUserRoleService.lambdaQuery().eq(SysUserRole::getSysRoleId, id).count();
            Assert.isTrue(userCount == 0, "该角色下存在用户，请先删除用户");
        }
        sysRoleService.lambdaUpdate().set(SysRole::getEnable, !sysRole.getEnable()).eq(SysRole::getId, id).update();
    }

    @Override
    public SysRoleRespVO getDetailById(Long sysRoleId) {
        SysRole sysRole = sysRoleService.getById(sysRoleId);
        SysRoleRespVO sysRoleRespVO = sysRole.convertToRespVO();
        List<SysUser> sysRoles = sysUserRoleMapper.queryByRole(sysRoleId);
        List<SysRoleRespVO.User> users = sysRoles.stream().map(x -> {
            SysRoleRespVO.User user = new SysRoleRespVO.User();
            user.setId(x.getId());
            user.setName(x.getNickName());
            return user;
        }).collect(Collectors.toList());
        sysRoleRespVO.setUsers(users);
        return sysRoleRespVO;
    }
}
